#include <my_header.h>

typedef struct share_value_s
{
    int ticket_num;
    pthread_mutex_t mutex;
}share_value_t;

void * threadFunc1(void * arg);
void * threadFunc2(void * arg);
/* usage */
int main(int argc, char *argv[])
{
    ARGS_CHECK(argc,1);
    share_value_t share_value;
    share_value.ticket_num = 20;
    pthread_mutex_init(&share_value.mutex,NULL);

    printf("Today ticket_num = %d\n",share_value.ticket_num);
    pthread_t tid[2];
    int ret_create1 = pthread_create(&tid[0],NULL,threadFunc1,&share_value);
    THREAD_ERROR_CHECK(ret_create1,"pthread_create 1");
    int ret_create2 = pthread_create(&tid[1],NULL,threadFunc2,&share_value);
    THREAD_ERROR_CHECK(ret_create2,"pthread_create 2");

    pthread_join(tid[0],NULL);
    pthread_join(tid[1],NULL);

    return 0;
}

void * threadFunc1(void * arg)
{
    share_value_t * pshare_value = (share_value_t *)arg;
    while(1)
    {
        pthread_mutex_lock(&pshare_value->mutex);
        if(pshare_value->ticket_num <= 0){
            pthread_mutex_unlock(&pshare_value->mutex);
            break;
        }
        pshare_value->ticket_num --;
        printf("Thread1 sells, ticket_num = %d\n",pshare_value->ticket_num);
        pthread_mutex_unlock(&pshare_value->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}

void * threadFunc2(void * arg)
{
    share_value_t * pshare_value = (share_value_t *)arg;
    while(1)
    {
        pthread_mutex_lock(&pshare_value->mutex);
        if(pshare_value->ticket_num <= 0){
            pthread_mutex_unlock(&pshare_value->mutex);
            break;
        }
        pshare_value->ticket_num --;
        printf("Thread2 sells ,ticket_num = %d\n",pshare_value->ticket_num);
        pthread_mutex_unlock(&pshare_value->mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}
